import React from 'react';

import CKModal from '../components/CKModal';
import AMUIReact,{
    Button,
    Input,
    FormGroup,
    Panel
} from 'amazeui-react';
import Fetch from '../common/Fetch';
import '../assets/css/manage/group_pur.less';

class Purview extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            data:[]
        };
        this.selectPur = this.props.params.pur || [];

        this.parentMenu = [];
        this.childMenu = [];
    }

    componentDidMount() {
        this.loadMenu();
    }

    loadMenu() {
        this.refs.modal.load('正在加载数据...');
        Fetch('/res/menu/get_purs',{},(res)=>{
            if (res.status) {
                this.setState({
                    data:res.data
                });
                this.refs.modal.closeModal();
            } else {
                this.refs.modal.alert('提示','加载分组数据出错');
            }
        },(e)=>{
            console.log(e);
            this.refs.modal.closeModal();
        });
    }

    clickHandler = () =>{
        $.map(this.refs,(item,key)=>{
            if (/^checked/.test(key)) {
                if (item.getChecked()) {
                    if (this.parentMenu.indexOf(item.props.parent_menu) === -1) {
                        this.parentMenu.push(item.props.parent_menu);
                    }
                    this.childMenu.push(item.getValue()) ;
                }
            }
        });

        var data = this.parentMenu.concat(this.childMenu);

        this.props.callback(data);
    };

    render() {
        return (
            <div>
                {this.state.data.map((item)=>{
                    return (
                        <Panel className="panel" header={item.menu_text} amStyle="primary">
                            <FormGroup>
                            {item.sub_menu.map((child)=>{
                                return (
                                    <Input ref={"checked_menu_"+child.menu_id}
                                           status={child.menu_id} type="checkbox"
                                           value={child.menu_id}
                                           label={child.menu_text}
                                           parent_menu={item.menu_id} inline
                                           defaultChecked={!(this.selectPur.indexOf(child.menu_id) === -1)}/>
                                );
                            })}
                            </FormGroup>
                        </Panel>
                    );
                })}
                <div className="sure_div">
                    <Button className="sure_btn" onClick={this.clickHandler} amStyle="primary">确定</Button>
                </div>
                <CKModal ref="modal"/>
            </div>
        );
    }
}

export default Purview;